//
//  ImageManager.m
//  FootPrint
//
//  Created by alex tao on 4/25/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "ImageManager.h"

@implementation ImageManager

static ImageManager * _sharedInstance = nil;

+ (ImageManager*) sharedInstance
{
	if (_sharedInstance == nil) {
        _sharedInstance = [[ImageManager alloc] init];
    }
	return _sharedInstance;
}

- (id)init
{
    self = [super init];
    if (self) {
        [self loadIndex];
    }
    return self;
}

- (void)dealloc
{
    [_indexArr release];
    [_rootDict release];
    [super dealloc];
}

- (NSString*) imageIndexFilePath
{
    return [NSString stringWithFormat:@"%@/image.idx", [self rootDirectory]];
}

- (NSString*) imageFileForName:(NSString*)name
{
    return [NSString stringWithFormat:@"%@/%@", [self rootDirectory], name];
}

- (NSString*) imageFileForImageId:(long long)imgId
{
    return [self imageFileForName:[NSString stringWithFormat:@"img_%lld", imgId]];
}

- (NSArray*) allImages
{
    return [[_indexArr copy] autorelease];
}

- (NSString *)rootDirectory
{
    if (nil == _rootDict) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *baseDir = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
        
        _rootDict = [[baseDir stringByAppendingPathComponent:@"CustomImage"] copy];
    }
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:_rootDict])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:_rootDict
                                  withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return _rootDict;
}

- (void) loadIndex
{
    _indexArr = [[NSMutableArray alloc] initWithContentsOfFile:[self imageIndexFilePath]];
    if (nil == _indexArr) {
        _indexArr = [[NSMutableArray alloc] initWithCapacity:4];
    }
}

- (void) saveIndex
{
    [_indexArr writeToFile:[self imageIndexFilePath] atomically:YES];
}

- (void) addImage:(UIImage*)image forImageId:(long long)imgId
{
    NSString * imgPath = [self imageFileForImageId:imgId];
    if (image) {
        NSData * imgData = UIImageJPEGRepresentation(image, 1.0);
        BOOL success = [imgData writeToFile:imgPath atomically:NO];
        if (success) {
            [_indexArr addObject:[NSString stringWithFormat:@"%lld", imgId]];
            [self saveIndex];
        }
    }
}

- (void) removeImageById:(long long)imgId
{
    NSString * imgPath = [self imageFileForImageId:imgId];
    [_indexArr removeObject:[NSString stringWithFormat:@"%lld", imgId]];
    
    [[NSFileManager defaultManager] removeItemAtPath:imgPath error:nil];
    [self saveIndex];
}

- (BOOL) imageExistForId:(long long)imgId
{
    if (imgId > 0) {
        return [_indexArr containsObject:[NSString stringWithFormat:@"%lld", imgId]];
    }
    return NO;
}

@end
